import { create } from 'zustand'

import {
  articleCreate,
  articleDelete,
  articleDetail,
  articleGetByPage,
  articleGetDetailsByIds,
  articleList,
  articleListAll,
  articleUpdate,
  articleUpsertOrder
} from '@/services/apis'
import http from '@/services/base'
import { ArticleType } from '@/types'

import type {
  ArticleItem,
  ArticleListResponse,
  ArticleMetaItem,
  CreateArticle,
  UpdateArticle
} from '../types'

type ArticleStore = {
  // 状态
  articles: ArticleMetaItem[]
  total: number
  currentPage: number
  pageSize: number
  loading: boolean
  searchTitle: string
  articleDetail: ArticleItem | null
  detailLoading: boolean
  submitLoading: boolean
  allArticles: ArticleMetaItem[]
  pageArticles: ArticleItem[]
  orderConfigLoading: boolean
  previewArticles: ArticleItem[]
  previewLoading: boolean

  // 操作
  getArticleList: (page?: number, pageSize?: number, title?: string, type?: string) => Promise<void>
  setSearchTitle: (title: string) => void
  handleSearch: (title: string, type: string) => void
  resetSearch: (type: string) => void
  handlePageChange: (page: number, pageSize?: number) => void
  createArticle: (data: CreateArticle) => Promise<boolean>
  updateArticle: (data: UpdateArticle) => Promise<boolean>
  deleteArticle: (id: string) => Promise<boolean>
  getArticleDetail: (id: string) => Promise<void>
  clearArticleDetail: () => void
  getAllArticles: (type?: string) => Promise<void>
  getArticlesByPage: (page: string) => Promise<void>
  upsertArticleOrder: (page: string, articleIds: string[]) => Promise<boolean>
  getArticleDetailsByIds: (ids: string[]) => Promise<void>
}

const useArticleStore = create<ArticleStore>((set, get) => ({
  // 初始状态
  articles: [],
  total: 0,
  currentPage: 1,
  pageSize: 10,
  loading: false,
  searchTitle: '',
  articleDetail: null,
  detailLoading: false,
  submitLoading: false,
  allArticles: [],
  pageArticles: [],
  orderConfigLoading: false,
  previewArticles: [],
  previewLoading: false,

  // 获取文章列表
  // @param page      页码，默认1
  // @param pageSize  每页数量，默认10
  // @param title     标题关键词，选填
  // @param type      文章类型，默认NORMAL，可指定为RESOURCE（资源共享时用）
  getArticleList: async (page = 1, pageSize = 10, title, type = ArticleType.NORMAL) => {
    const searchTitle = title !== undefined ? title : get().searchTitle
    set({ loading: true })
    try {
      // 明确响应数据类型：分页列表，type区分NORMAL和RESOURCE
      const response = await http.post<ArticleListResponse>(articleList, {
        page,
        pageSize,
        title: searchTitle,
        type // 传递type参数，默认为NORMAL
      })
      if (response && response.data) {
        set({
          articles: response.data.list,
          total: response.data.total,
          currentPage: page,
          pageSize
        })
      }
    } catch (error) {
      console.error('获取文章列表失败:', error)
      set({ articles: [], total: 0 })
    } finally {
      set({ loading: false })
    }
  },

  // 设置搜索标题
  setSearchTitle: (title: string) => {
    set({ searchTitle: title })
  },

  // 处理搜索（搜索并重置到第一页）
  // handleSearch: 根据关键词搜索并支持type分类（如RESOURCE）
  handleSearch: (title: string, type: string = ArticleType.NORMAL) => {
    set({ searchTitle: title, currentPage: 1 })
    get().getArticleList(1, get().pageSize, title, type)
  },

  // 重置搜索条件
  // resetSearch: 重置条件同时可指定type
  resetSearch: (type: string = ArticleType.NORMAL) => {
    set({ searchTitle: '', currentPage: 1 })
    get().getArticleList(1, get().pageSize, '', type)
  },

  // 处理分页变化
  handlePageChange: (page: number, pageSize?: number) => {
    const updates: { currentPage: number; pageSize?: number } = { currentPage: page }
    if (pageSize !== undefined) {
      updates.pageSize = pageSize
    }
    set(updates)
    get().getArticleList(page, pageSize || get().pageSize, get().searchTitle)
  },

  // 创建文章
  createArticle: async (data: CreateArticle) => {
    set({ submitLoading: true })
    try {
      await http.post(articleCreate, data)
      await get().getArticleList(1, get().pageSize, '') // 创建成功后回到第一页并清空搜索条件
      set({ searchTitle: '' })
      return true
    } catch (error) {
      console.error('创建文章失败:', error)
      return false
    } finally {
      set({ submitLoading: false })
    }
  },

  // 更新文章
  updateArticle: async (data: UpdateArticle) => {
    set({ submitLoading: true })
    try {
      await http.post(articleUpdate, data)
      await get().getArticleList(get().currentPage, get().pageSize) // 更新成功后刷新当前页
      return true
    } catch (error) {
      console.error('更新文章失败:', error)
      return false
    } finally {
      set({ submitLoading: false })
    }
  },

  // 删除文章（方案A：自动处理分页逻辑）
  deleteArticle: async (id: string) => {
    try {
      await http.post(articleDelete, { id })

      // 方案A核心逻辑：自动处理分页
      const state = get()
      const currentList = state.articles
      const currentPage = state.currentPage
      const pageSize = state.pageSize

      // 如果删除的是当前页最后一条且不是第一页，返回上一页
      if (currentList.length === 1 && currentPage > 1) {
        await get().getArticleList(currentPage - 1, pageSize, state.searchTitle)
      } else {
        // 否则刷新当前页
        await get().getArticleList(currentPage, pageSize, state.searchTitle)
      }

      return true
    } catch (error) {
      console.error('删除文章失败:', error)
      return false
    }
  },

  // 获取文章详情
  getArticleDetail: async (id: string) => {
    set({ detailLoading: true, articleDetail: null })
    try {
      // 明确响应数据类型：文章详情
      const response = await http.post<ArticleItem>(articleDetail, { id })
      if (response && response.data) {
        set({ articleDetail: response.data })
      }
    } catch (error) {
      console.error('获取文章详情失败:', error)
      set({ articleDetail: null })
    } finally {
      set({ detailLoading: false })
    }
  },

  // 清除文章详情
  clearArticleDetail: () => {
    set({ articleDetail: null })
  },

  // 获取所有文章（如资源共享和配置排序需设type为RESOURCE，默认NORMAL）
  getAllArticles: async (type = ArticleType.NORMAL) => {
    set({ orderConfigLoading: true })
    try {
      // 调用listAll接口获取所有文章，传递type参数，可取RESOURCE
      const response = await http.post<ArticleMetaItem[]>(articleListAll, { type })
      if (response && response.data) {
        set({ allArticles: response.data })
      }
    } catch (error) {
      console.error('获取所有文章列表失败:', error)
    } finally {
      set({ orderConfigLoading: false })
    }
  },

  // 根据页面获取文章
  getArticlesByPage: async (page: string) => {
    set({ orderConfigLoading: true })
    try {
      // 明确响应数据类型：页面文章列表
      const response = await http.post<ArticleItem[]>(articleGetByPage, { page })
      if (response && response.data) {
        set({ pageArticles: response.data })
      }
    } catch (error) {
      console.error(`获取页面 ${page} 文章失败:`, error)
      set({ pageArticles: [] })
    } finally {
      set({ orderConfigLoading: false })
    }
  },

  // 创建或更新文章顺序
  upsertArticleOrder: async (page: string, articles: string[]) => {
    set({ submitLoading: true })
    try {
      await http.post(articleUpsertOrder, { page, articles })
      return true
    } catch (error) {
      console.error('更新文章顺序失败:', error)
      return false
    } finally {
      set({ submitLoading: false })
    }
  },

  // 获取预览文章
  getArticleDetailsByIds: async (ids: string[]) => {
    set({ previewLoading: true, previewArticles: [] })
    try {
      const response = await http.post<ArticleItem[]>(articleGetDetailsByIds, {
        ids
      })
      if (response && response.data) {
        set({ previewArticles: response.data })
      }
    } catch (error) {
      console.error('获取预览文章失败:', error)
      set({ previewArticles: [] })
    } finally {
      set({ previewLoading: false })
    }
  }
}))

export default useArticleStore
